<?php
namespace App\Http\Controllers\Store;

use App\Http\Controllers\Controller;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use App\Http\Requests\StoreRegisterRequest;
use App\Http\Requests\StoreMasterRequest;
use App\Http\Requests\StoreVillageRequest;
use App\Models\ClientUser;
use App\Models\ClientUserTicket;
use App\Exceptions\ApiException;
use App\Models\ShopStore;
use App\Models\ShopStoreMaster;
use App\Models\ShopStoreClass;
use App\Models\ShopStoreRoles;
use App\Models\HouseDistrict;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\PasswordBackRequest;
class UserController extends Controller {
	
	public function login(LoginRequest $request){
		$username = $request->input('username');
		$password = $request->input('password');
		$clientUser = new ClientUser();
		$uid = $clientUser->checkLogin($username,$password,[4]);
		$data = login($uid,1);
		return json_success('OK',$data);
	}
	
	public function logout(BasicRequest $request){
		$var = logout();
		return json_return($var,'','已退出登录');
	}

    private function check_login(){
        $clientUserTicket = new ClientUserTicket();
        $user = $clientUserTicket->checkLogin();
        if($user->type != 4){
            throw new ApiException('用户角色错误，拒绝登录');
        }
        $user->store_id = ShopStoreRoles::where(['uid'=>$user->id])->value('store_id');
        return $user;
    }
    /**
     * @param RegisterRequest $request
     * @return array
     * @throws ApiException
     * 商家注册
     */
    public function register(RegisterRequest $request){
        $username = $request->input('username');
        $mobile = $request->input('mobile');
        $password = $request->input('password');
        $sms_code = $request->input('sms_code');	// 短信验证码
        // 验证短信码
        $code = cache('register_sms_'.$mobile);
        if(strcmp($code,$sms_code) !== 0){
            throw new ApiException('短信验证码错误(可重复输入)');
        }
        $clientUser = new ClientUser();

        $uid = $clientUser->SellerRegister($username,$mobile,$password);

        //wechat_update($uid);
        $data = login($uid);
        return json_return($uid,'','注册成功',$data);
    }
    /**
     * @param RegisterRequest $request
     * @return array
     * @throws ApiException
     * 商家注册第二步——获取商家已填写的资料
     */
    public function datum(){
        $user = self::check_login();
        $store_info=ShopStore::where(['uid'=>$user->id])->first();
        if($store_info->status ==5){
            throw new ApiException('店铺已冻结');
        }
        $master_info = ShopStoreMaster::where(['store_id'=>$store_info->id])->select(['master_name','master_mobile','master_code','idcard_top_img','idcard_under_img','business_img','remark'])->first();
        
		$store_info->village_name = HouseDistrict::where(['id'=>$store_info->village_id])->value('name');
		$store_info->store_class_name = ShopStoreClass::getClassNameById($store_info->store_class);
        $store_info->master_info = $master_info?:(object)array();
        $store_info->class_list = ShopStoreClass::where(['is_del'=>0])->select('id','store_class_name','store_class_type')->get()->groupBy('store_class_type');

        return json_sussess_obj('OK',$store_info);
    }
    /**
     * @param RegisterRequest $request
     * @return array
     * @throws ApiException
     * 商家注册第二步——提交店主信息
     */
    public function register_master(StoreMasterRequest $request){
        $isMob="/^1[3-5,8]{1}[0-9]{9}$/";
        $isTel="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if(!preg_match($isMob,$request->input('master_mobile')) && !preg_match($isTel,$request->input('master_mobile')))
        {
            return json_error('请输入手机号或者座机号');
        }
        $user = self::check_login();
        $input['master_name']=$request->input('master_name');
        $input['master_mobile']=$request->input('master_mobile');
        $input['master_code']=$request->input('master_code');
        $input['idcard_top_img']=$request->input('idcard_top_img');
        $input['idcard_under_img']=$request->input('idcard_under_img');
        $input['store_id']=$user->store_id;
        $input['uid']=$user->id;
        $update = ShopStoreMaster::updateOrCreate(['store_id'=>$user->store_id],$input)->id;
        if($update) {
            return json_success('操作成功');
        }else{
            return json_error('操作失败');
        }
    }
    /**
     * @param RegisterRequest $request
     * @return array
     * @throws ApiException
     * 商家注册第二步——提交店铺信息
     */
    public function register_store(StoreRegisterRequest $request){
        $isMob="/^1[3-5,8]{1}[0-9]{9}$/";
        $isTel="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if(!preg_match($isMob,$request->input('store_mobile')) && !preg_match($isTel,$request->input('store_mobile')))
        {
            return json_error('请输入手机号或者座机号');
        }
        $user = self::check_login();
        $input['store_name'] = $request->input('store_name');
        $input['store_mobile'] = $request->input('store_mobile');
        $input['store_type'] = $request->input('store_type');
        $input['store_class'] = $request->input('store_class');
        $input['province_id'] = $request->input('province_id');
        $input['city_id'] = $request->input('city_id');
        $input['area_id'] = $request->input('area_id');
        $input['village_id'] = $request->input('village_id');
        $input['village_ids'] = $request->input('village_id');
        $input['lat'] = $request->input('lat');
        $input['lng'] = $request->input('lng');
        $input['address'] = $request->input('address');
        $input['status'] = 3;

        $master['business_img'] = $request->input('business_img');

        $return=DB::transaction(function () use($input,$master,$user){
            ShopStoreMaster::updateOrCreate(['store_id' => $user->store_id], $master);
            ShopStore::updateOrCreate(['id' => $user->store_id], $input);
            return true;
        });
        if($return) {
            return json_success('操作成功');
        }else{
            return json_error('操作失败');
        }
    }

    /**
     * @param RegisterRequest $request
     * @return array
     * @throws ApiException
     * 商家注册第二步——获取当前小区
     */
    public function register_village(StoreVillageRequest $request){
        $area_id = $request->input('area_id');
        $lat = $request->input('lat');
        $lng = $request->input('lng');
        $data = HouseDistrict::select(DB::raw('id,name,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))->where(['area_id'=>$area_id])->orderBy('distance','asc')->limit(10)->get();
        return json_success('OK',$data);
    }

    /**
     * @param PasswordBackRequest $request
     * @return array
     * @throws ApiException
     * 忘记密码，使用短信码重置密码
     */
    public function password_reset(PasswordBackRequest $request){
        $mobile = $request->input('mobile');
        $password_new = $request->input('password');
        $sms_code = $request->input('sms_code');
        // 验证短信码
        $code = cache('store_password_reset_sms_'.$mobile);
        if(strcmp($code,$sms_code) !== 0){
            throw new ApiException('短信验证码错误(可重复输入)');
        }
        $clientUser = new ClientUser();
        $user = $clientUser->where(['mobile'=>$mobile,'type'=>4])->first();
        if(empty($user)){
            throw new ApiException('找不到该用户');
        }
        $password_gen = $clientUser->passwordEncodeSalt($password_new,$user->salt);
        $var = ClientUser::where(['mobile'=>$mobile,'type'=>4])->update(['password'=>$password_gen]);
        return json_return($var,'','密码重置成功，请使用新密码登录');
    }

    /**
     * @param Request $request
     * @return array
     * 发送忘记密码短信码
     */
    public function password_reset_sms(Request $request){
        $mobile = $request->input('mobile');
        $cache_key = 'store_password_reset_sms_'.$mobile;
        \Validator::make($request->all(),[
            'mobile'		=> 'required|size:11',
        ],[
            'mobile.required'	=> '请填写11位手机号码',
            'mobile.size'		=> '请填写11位手机号码',
        ])->validate();
        if(cache($cache_key.'_action')){
            throw new ApiException('操作繁忙，请耐心等待');
        }
        if(env('APP_ENV') == 'online'){
            $code = create_verify_code(4);
            $timeout = 1;		// 60秒
            $var = send_message($mobile,'验证码',[$code,30]);
        }else{
            $code = '8888';
            $timeout = 0.05;	// 3秒
            $var = true;
        }
        cache([$cache_key=>$code],30);
        cache([$cache_key.'_action'=>$code],$timeout);	// 操作单独缓存
        return json_return($var,'','短信已发送');
    }
}